package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.feign.ArticleFeign;
import com.heima.comment.service.ComentService;
import com.heima.common.constans.message.MessageConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojo.ApComment;
import com.heima.model.comment.pojo.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApUserThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ComentServiceImpl implements ComentService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ArticleFeign articleFeign;
    @Override
    public ResponseResult add(CommentSaveDto dto) {
        //检查参数
        if (dto==null||dto.getArticleId()==null||dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140字");
        }
        //获取登录用户，判断是否登录
        ApUser apUser = ApUserThreadLocalUtils.getUser();
        if (apUser==null||apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        /*Query query= Query.query(Criteria.where("authorId").is(apUser.getId()).and("entryId").is(dto.getArticleId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);*/


            ApComment   apComment=new ApComment();
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser.getName());
            apComment.setContent(dto.getContent());
            apComment.setEntryId(dto.getArticleId());
            apComment.setCreatedTime(new Date());
            apComment.setImage(apUser.getImage());
            apComment.setType((short) 0);

            apComment.setLikes(0);
            apComment.setReply(0);

            ResponseResult<ApArticle> result = articleFeign.findById(dto.getArticleId());
            if (result.getCode()!=AppHttpCodeEnum.SUCCESS.getCode()&&result.getData()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        ApArticle article = result.getData();
        apComment.setChannelId(article.getChannelId());
        apComment.setUpdatedTime(new Date());

        //发送消息进行实时流更新
        sendmessage(dto,1);
        //保存评论
        return ResponseResult.okResult( mongoTemplate.save(apComment));
    }

    @Autowired
    KafkaTemplate kafkaTemplate;
    //发送消息进行实时流更新
    private void sendmessage(CommentSaveDto dto, int i) {
        UpdateArticleMess mess=new UpdateArticleMess();
        mess.setAdd(i);
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);
        kafkaTemplate.send(MessageConstants.HOT_ARTICLE_BEHAVIOR_SEND_TOPIC,JSON.toJSONString(mess));
    }


    /**
     *给评论点赞或取消点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //检查参数
        if (dto==null||dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = ApUserThreadLocalUtils.getUser();
        if (apUser==null||apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询评论表，判断评论是否存在
        Query query= Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询点赞表
        Query query1 = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(dto.getCommentId()));
        ApCommentLike commentLike = mongoTemplate.findOne(query1, ApCommentLike.class);

        //如果存在则取消点赞
        if (commentLike==null){
            //如果不存在则创建
            commentLike=new ApCommentLike();
            commentLike.setAuthorId(apUser.getId());
            commentLike.setCommentId(dto.getCommentId());
            //保存信息
            ApCommentLike save = mongoTemplate.save(commentLike);
            //点赞数加一
            apComment.setLikes(apComment.getLikes()+1);
        }else {

            mongoTemplate.remove(query1,ApCommentLike.class);
            //点赞数减一
            if (apComment.getLikes()>0){
                apComment.setLikes(apComment.getLikes()-1);
            }
        }


        return ResponseResult.okResult(mongoTemplate.save(apComment));
    }

    /**
     * 根据文章id，获取文章评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //检查参数
        if (dto==null||dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize()==0||dto.getSize()>50){
            dto.setSize(50);
        }
        //分页查询评论表
        Query query=Query.query(Criteria.where("entryId").is(dto.getArticleId()));

        //排序查询
        query.limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC,"likes"));

        List<ApComment> list = mongoTemplate.find(query, ApComment.class);
        //判断用户是否登录
        ApUser apUser = ApUserThreadLocalUtils.getUser();
        if (apUser==null||apUser.getId()==0){
            return ResponseResult.okResult(list);
        }

        List<String> collect = list.stream().map(apComment -> apComment.getId()).collect(Collectors.toList());
        //如果登录则用户的评论高亮显示

        Query query2=Query.query(Criteria.where("commentId").in(collect).and("authorId").is(apUser.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query2, ApCommentLike.class);

        ArrayList<ApCommentVo> list1=new ArrayList<>();
        for (ApComment apComment : list) {
            ApCommentVo apCommentVo = JSON.parseObject(JSON.toJSONString(apComment), ApCommentVo.class);
            for (ApCommentLike commentLike : apCommentLikes) {
                if (apComment.getEntryId().equals(apCommentVo.getEntryId())){
                    apCommentVo.setOperation((short) 0);
                    list1.add(apCommentVo);
                    break;
                }
            }
        }

        return ResponseResult.okResult(list1);
    }
}
